//
//  Y2Localization.m
//  Pods-Unity-iPhone
//
//  Created by MacPro on 2021/1/14.
//

#import "Y2Localization.h"

NSString *const Y2LanguageCodeEn = @"en";
NSString *const Y2LanguageCodeZhHans = @"zh-Hans";
NSString *const Y2LanguageCodeZhHant = @"zh-Hant";
NSString *const Y2LanguageCodeUnknown = @"unknown";

@implementation Y2Localization

+ (instancetype)shared {
    static dispatch_once_t predicate;
    static Y2Localization *instance;
    dispatch_once(&predicate, ^{
        instance = [[Y2Localization alloc] init];
        instance.currentLanguage = [Y2Localization localizedLanguage];
    });
    return instance;
}

- (void)setCurrentLanguage:(Y2Language)currentLanguage {
    _currentLanguage = currentLanguage;
}

+ (NSString *)languageCode:(Y2Language)language {
    switch (language) {
        case Y2LanguageEn:
            return Y2LanguageCodeEn;
        case Y2LanguageZhHans:
            return Y2LanguageCodeZhHans;
        case Y2LanguageZhHant:
            return Y2LanguageCodeZhHant;
        case Y2LanguageUnknown:
            return Y2LanguageCodeUnknown;
    }
}

+ (Y2Language)language:(NSString *)code {
    if ([code hasPrefix:Y2LanguageCodeEn]) {
        return Y2LanguageEn;
    } else if ([code hasPrefix:Y2LanguageCodeZhHans]) {
        return Y2LanguageZhHans;
    } else if ([code hasPrefix:Y2LanguageCodeZhHant]) {
        return Y2LanguageZhHant;
    } 
    return Y2LanguageUnknown;
}

+ (Y2Language)localizedLanguage {
    // 返回的也是国际通用语言Code+国际通用国家地区代码
    NSString *languageCode = [NSLocale preferredLanguages][0];
    Y2Language language = [self language:languageCode];
    return language;
}

@end


@implementation NSString (Y2Localized)

+ (instancetype)y2Localized:(NSString *)localizable bundle:(NSBundle *)bundle table:(NSString *)tableName{
    NSString *languageCode = [Y2Localization languageCode:[Y2Localization shared].currentLanguage];
    NSString *bundlePath = [bundle pathForResource:languageCode ofType:@"lproj"];
    NSBundle *localizedBundle = [NSBundle bundleWithPath:bundlePath];
    NSString *result = [localizedBundle localizedStringForKey:localizable value:nil table:tableName];
    if (result == nil) { return localizable; }
    return result;
}

@end
